package com.juzipi.framework.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.juzipi.common.constant.properties.PropertiesVariable;
import com.juzipi.inter.mapper.RoleMapper;
import com.juzipi.inter.mapper.UserMapper;
import com.juzipi.inter.pojo.Role;
import com.juzipi.inter.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 注意不是对应loginUser实体类，实际上也是对应User的Service
 */
@Service
public class LoginUserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;


    private static final long MILLIS_SECOND = 1000;//秒

    private static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;//分钟



    /**
     * 验证登录的账号是否存在
     * @param username
     * @return
     */
    public User checkUser(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
    }


    /**
     * 根据登陆的用户的roleid查询对应的角色集合
     * @param roleId
     * @return 角色集合
     */
    public List<Role> queryUserRoleList(Long roleId) {
        return roleMapper.selectList(new QueryWrapper<Role>().lambda().in(Role::getId, roleId));
    }


    /**
     * 退出时插入最后登录时间
     * @param username
     */
    public void logout(String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        user.setLastLoginTime(new Date());
        userMapper.updateById(user);
    }


    /**
     * 验证用户是否未锁定
     * @param username 登陆的用户
     */
    public void lockUserByUsername(String username){
        //如果达到了限制就把用户锁定
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername,username));
        user.setNonLocked(false);
        userMapper.updateById(user);
    }


    /**
     * 验证用户账号是否还在锁定中
     * @param user
     * @return
     */
    public Boolean checkLockedTime(User user){
        //因为锁定的时候更改了用户，所以用户的 更新时间 也变动了，更新时间就是锁定的时间
        long userLockTime = user.getUpdateTime().getTime();
        long currentTimeMillis = System.currentTimeMillis();
        //判断锁定时间和现在的时间相差大于 xx分钟 左右就更新用户信息解锁用户
        if (currentTimeMillis - userLockTime >= MILLIS_MINUTE * PropertiesVariable.userLockTime){
            //改为true
            user.setNonLocked(true);
            userMapper.updateById(user);
            return true;
        }
        return false;
    }
}
